<template>
  <el-dialog
    :title="formData.id? '编辑部门' :'新增部门'"
    :visible="visible"
    label-width="120px"
    @close="$emit('update:visible',false)"
  >
    <el-form ref="formData" :model="formData" :rules="rules" label-width="120px" class="demo-ruleForm">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="formData.name" placeholder="2-10个字符" style="width: 80%;" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="formData.code" placeholder="2-10个字符" style="width: 80%;" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="managerId">
        <el-select v-model="formData.managerId" placeholder="请选择负责人" style="width: 80%;">
          <el-option v-for="item in userList" :key="item.id" :label="item.username" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="formData.introduce" style="width: 80%;" rows="4" type="textarea" placeholder="1-300个字符之间" />
      </el-form-item>
      <el-form-item>
        <el-row type="flex" justify="center">
          <el-col :span="12">
            <el-button size="mini" type="primary" @click="submitForm">确定</el-button>
            <el-button size="mini" @click="$emit('update:visible',false)">取消</el-button>
          </el-col>

        </el-row>

      </el-form-item>
    </el-form>

  </el-dialog>
</template>

<script>
import { addDepAPI, departmentAPI, editDepAPI, findDepAPI, responsibleAPI } from '@/api/department'
export default {
  props: {
    visible: Boolean,
    currentId: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      formData: {
        name: '',
        code: '',
        managerId: '',
        introduce: ''
      },
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' },
          {
            validator: async(rule, value, callback) => {
              // 调用获取全部部门接口
              const res = await departmentAPI()
              // 当有id 时候就是编辑，编辑时候过滤掉自己，不会提示错误
              let depList = res.data.data
              if (this.formData.id) {
                depList = depList.filter(item => item.id !== this.formData.id)
              }

              // some 方法是在数组里面判断是否有满足条件的,有则返回true
              const isJudgment = depList.some(item => item.name === value)
              // 判断是否有该部门存在
              if (isJudgment) {
                callback(new Error('部门名称已存在'))
              } else {
                callback()
              }
            }, trigger: 'blur'
          }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' },
          {
            validator: async(rule, value, callback) => {
              const res = await departmentAPI()
              // 当有id 时候就是编辑，编辑时候过滤掉自己，不会提示错误
              let depList = res.data.data
              if (this.formData.id) {
                depList = depList.filter(item => item.id !== this.formData.id)
              }

              const isJudgment = depList.some(item => item.code === value)

              if (isJudgment) {
                callback(new Error('部门编码已存在'))
              } else {
                callback()
              }
            }, trigger: 'blur'
          }
        ],
        managerId: [{ required: true, message: '部门负责人不能为空', trigger: 'chenge' }],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
        ]
      },
      userList: []
    }
  },
  watch: {
    visible(newData) {
      if (!newData) {
        this.$refs.formData.resetFields()
        this.formData = {
          name: '',
          code: '',
          managerId: '',
          introduce: ''
        }
      }
    }
  },
  created() {
    this.responsibleList()
  },
  methods: {
    async responsibleList() {
      // 调用负责人列表接口
      const res = await responsibleAPI()
      this.userList = res.data.data
    },
    async submitForm() {
      // 校验表单
      this.$refs.formData.validate()
      let res = ''
      if (!this.formData.id) {
        // 调用新增部门接口
        res = await addDepAPI({
          ...this.formData,
          pid: this.currentId
        })
      } else {
        res = await editDepAPI({
          ...this.formData
        }, this.formData.id)
      }

      // 向父组件传递 visible = false
      this.$emit('update:visible', false)
      // 向父组件传递 一个事件updatePage
      this.$emit('updatePage')
      this.$message.success(res.data.message)
    },
    async depDetail(id) {
      // 调用查询部门详情接口
      const res = await findDepAPI(id)
      // 把获取到数据给formData ，同时渲染页面上去
      this.formData = res.data.data
    }
  }
}
</script>

<style>

</style>
